package indi.liangli;


import indi.liangli.registry.IRegistryCenter;
import indi.liangli.registry.RegistryZkImpl;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.net.*;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * InitializingBean 对应创建后通过 afterPropertiesSet 设置属性
 * ApplicationContextAware 能够获取spring 应用上下文
 */
@Component
public class RpcServer implements ApplicationContextAware, InitializingBean {
    private int port;
    //标记rpc的接口实现类map
    private Map<String,Object> handlerMap = new HashMap<>();


    private IRegistryCenter registryCenter = new RegistryZkImpl();

    public RpcServer(int port){
        this.port = port;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        //容器启动后需要做的事情
        //创建netty 服务端  服务端接收客户端请求
        //boss 线程分发任务，work线程处理任务，调用到pipelin上，进行处理

        //默认cpu核数两倍
        EventLoopGroup boss = new NioEventLoopGroup();
        EventLoopGroup work = new NioEventLoopGroup();
        ServerBootstrap server = new ServerBootstrap();
        try {
            server.group(boss,work)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<Channel>() {
                        @Override
                        protected void initChannel(Channel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            //添加对象编解码器 支持对象序列化
                            pipeline.addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(null)))
                                    .addLast(new ObjectEncoder())
                                    .addLast(new ProcesserHandler(handlerMap));
                        }
                    });

            ChannelFuture channelFuture = server.bind(port).sync();
            System.out.println("服务端启动成功 litener port "+port);
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
            boss.shutdownGracefully();
            work.shutdownGracefully();
        }

    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        //获取容器中所有加入rpcService的类
        Map<String, Object> beansWithAnnotation = applicationContext.getBeansWithAnnotation(RpcService.class);
        if(beansWithAnnotation.isEmpty()){
            return;
        }
        for (Object bean : beansWithAnnotation.values()) {
            RpcService annotation = bean.getClass().getAnnotation(RpcService.class);
            String className =  annotation.value().getName();
            if(!StringUtils.isEmpty(annotation.version())){
                className +="_"+annotation.version();
            }

            handlerMap.put(className,bean);
            //服务注册 服务名称为className 服务value ip:port
            registryCenter.registry(className,getAddress()+":"+port);
        }

    }


    private String getAddress(){
        InetAddress inetAddress = null;
        try {
            inetAddress = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return inetAddress.getHostAddress();
    }
}
